import { forwardRef, useState, useEffect, useMemo, useImperativeHandle } from 'react';
import { Radio, Table, Button } from 'antd';
import { InbizIcon, getEditor } from '@inbiz/utils';
import { TextWidget, getMessage } from '@inbiz/react';
import Paginations from './Pagenations';
import Spin from '../../Spin';
import NoData from '../../NoData';
import ProcessIcon from '../../ProcessIcon';
import { goto, goPopupDetail, goDrawerDetail } from '../../../../commonUtils';
import './ProcessApply.less';

const ProcessApply = forwardRef((props: any, ref) => {
  const {
    data,
    openMode,
    openPopUpHeight,
    openPopUpWidth,
    drawerWidth,
    choosedTabKey,
    searchBarRef,
    userInfo,
    rangeConfig,
    processGroup,
    getApplyCategory,
    getApplyList,
  } = props;

  // 流程列表loading
  const [loading, setLoading] = useState(false);
  // 流程分组
  const [applyCatogory, setApplyCatogory] = useState<{ name: string; id: string }[]>([]);
  // 流程列表
  const [applyList, setApplyList] = useState<{ name: string; id: string; proLcon: string }[]>([]);
  // 流程列表分页
  const [pageData, setPageData] = useState({
    pageIndex: 1,
    pageSize: 50,
    total: 0,
  });
  // 当前分组名称
  const [processGroupName, setProcessGroupName] = useState('');
  // 数据展示方式
  const [showTableView, setShowTableView] = useState(sessionStorage.getItem('showTableInfo') ? sessionStorage.getItem('showTableInfo') == '1' ? true : false : false);
  // 是否为设计器
  const isEditor = getEditor();

  // 获取分组数据的方法
  const getApplyCategoryData = async () => {
    let categoryData = await getApplyCategory({
      userId: userInfo?.ID, type: 'apply', groupType: 'Group', dptKey: rangeConfig == 'all' || processGroup?.selectedRows?.length == 0
        ? ''
        : processGroup?.groupGuid ?? '',
    })
    if (categoryData && categoryData?.details && categoryData?.details?.GroupData) {
      setApplyCatogory([
        {
          id: '',
          name: 'processCenter.all',
        },
        ...categoryData.details.GroupData,
      ]);
    }
  }

  // 获取流程列表数据的方法
  const searchApply = async (pageIndex: number, pageSize: number, processName?: string, pGroupName?: string) => {
    let _applyList = await getApplyList({
      pageIndex,
      pageSize,
      processName,
      processGroupName: pGroupName,
      userId: userInfo?.ID,
      dptKey:
        rangeConfig == 'all' || processGroup?.selectedRows?.length == 0
          ? ''
          : processGroup?.groupGuid ?? '',
    })
    if (_applyList && _applyList?.details && _applyList?.details?.rows) {
      setApplyList(_applyList.details.rows);
      setPageData({
        pageIndex,
        pageSize,
        total: _applyList.details.total,
      });
    } else {
      setApplyList([]);
      setPageData({
        pageIndex: 1,
        pageSize,
        total: 0,
      });
    }
  };

  // 获取onMount时的数据
  const getInitData = async () => {
    sessionStorage.removeItem('batchApproval');
    setLoading(true);
    await getApplyCategoryData();
    await searchApply(1, 50, '');
    setLoading(false);
  };

  // 获取当前分组下的流程数据
  const getCurrentGroupApplyData = async (value: string) => {
    setProcessGroupName(value);
    setLoading(true);
    await searchApply(
      1,
      pageData.pageSize,
      searchBarRef?.current?.searchText,
      value,
    );
    setLoading(false);
  }

  // 跳转至流程详情
  const goDetail = (item: any, e: any) => {
    if (openMode == 'newPage') {
      goto(
        {
          processDefinitionId: item.processDefinitionId,
          inItiateApplication: true,
          siteType: 0,
        },
        '1',
        'web',
        e,
        '',
        () => { },
        setLoading,
      );
    } else if (openMode == 'popUp') {
      goPopupDetail(item, choosedTabKey, openPopUpHeight, openPopUpWidth, setLoading);
    } else if (openMode == 'rightDrawer') {
      goDrawerDetail(item, choosedTabKey, drawerWidth, setLoading);
    }
  };

  // 刷新当前流程列表数据
  const onRefresh = async () => {
    setLoading(true);
    await searchApply(
      pageData.pageIndex,
      pageData.pageSize,
      searchBarRef?.current?.searchText,
      processGroupName,
    );
    setLoading(false);
  };

  // 改变视图方式
  const onViewChange = () => {
    if (isEditor) {
      return;
    }
    sessionStorage.setItem('showTableInfo', !showTableView ? '1' : '0');
    setShowTableView(!showTableView);
  }

  // table view时的columns
  const columns = useMemo(() => {
    return [
      {
        title: '',
        width: 52,
        dataIndex: 'ProLcon',
        render: (text: string) => (
          <ProcessIcon
            processIconInfo={text ? text?.trim() : 'font_family'}
            style={{ fontSize: 16 }}
            imgStyle={{ width: 16, height: 16 }}
          />
        ),
      },
      {
        title: getMessage('processCenter.processName'),
        dataIndex: 'ProcessName',
        render: (text: string, record: any) => {
          return (
            <div>
              <span
                onClick={(e) => {
                  goDetail(record, e);
                }}
                className="processName"
              >
                {text}
              </span>
            </div>
          );
        },
      },
      {
        title: getMessage('processCenter.group'),
        dataIndex: 'groupName',
      },
      {
        title: getMessage('processCenter.version'),
        dataIndex: 'ProcessVersion',
      },
    ];
  }, []);

  // 分页组件
  const pageComponent = (
    <div className="pagenation">
      <Paginations
        pageData={pageData}
        onChange={async (page: number, pageSize: number) => {
          if (isEditor) {
            return;
          }
          setLoading(true);
          await searchApply(page, pageSize, searchBarRef?.current?.searchText, processGroupName);
          setLoading(false);
        }}
      />
    </div>
  )

  // onMount
  useEffect(() => {
    if (userInfo?.ID) {
      getInitData();
    }
  }, [userInfo?.ID, rangeConfig]);

  // 向外暴露的方法
  useImperativeHandle(ref, () => ({
    searchApply: async (text: string) => {
      setLoading(true);
      setPageData({
        pageIndex: 1,
        pageSize: pageData.pageSize,
        total: 0,
      });
      setProcessGroupName('');
      await searchApply(
        1,
        pageData.pageSize,
        text || searchBarRef?.current?.searchText,
      )
      setLoading(false);
    },
    getApplyCategory: async () => {
      setLoading(true);
      await getApplyCategoryData();
      setLoading(false);
    },
    setProcessGroupName,
  }));

  return (
    <div className="processApply">
      <div className="catogory">
        <div>
          {!(data?.processGroup === false) && (
            <Radio.Group
              defaultValue=""
              value={processGroupName}
              onChange={(e) => { getCurrentGroupApplyData(e.target.value) }}
              buttonStyle="solid"
              optionType="button"
            >
              {applyCatogory.map((item) => {
                return (
                  <Radio.Button key={item.id} value={item.id}>
                    <span title={getMessage(item.name)}>
                      <TextWidget>{item.name}</TextWidget>
                    </span>
                  </Radio.Button>
                );
              })}
            </Radio.Group>
          )}
        </div>
        <div className="process-apply-refresh">
          <Button shape="round" onClick={onRefresh}>
            <InbizIcon type="icon-shuaxin" style={{ fontSize: '16px' }} />
            <TextWidget>processCenter.refresh</TextWidget>
          </Button>
        </div>
        <div
          onClick={onViewChange}
          style={{ cursor: 'pointer', height: 32, display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: 32 }}
        >
          <InbizIcon
            type={showTableView ? 'icon-ic-modular' : 'icon-process-shituqiehuan'}
            style={{ fontSize: 24, color: '#666', transition: '.3s' }}
          />
        </div>
      </div>
      <Spin spinning={loading}>
        {
          applyList?.length > 0
            ?
            showTableView
              ?
              <>
                <div className="tableInfo">
                  <Table columns={columns} dataSource={applyList} key="ProcessKey" pagination={false} />
                </div>
                {pageComponent}
              </>
              :
              <>
                <div className="apply">
                  <div className="applyContainer">
                    {applyList.map((item: any) => {
                      return (
                        <div className="cardItemContainer" key={item?.taskId || ''}>
                          <div
                            className="applyItem"
                            onClick={(e) => {
                              goDetail(item, e)
                            }}
                            key={item.ProcessKey}
                          >
                            <div className="applyImage">
                              <ProcessIcon
                                processIconInfo={item?.ProLcon ? item?.ProLcon?.trim() : 'font_family'}
                                style={{ fontSize: 30 }}
                                imgStyle={{ width: 30, height: 30 }}
                                base={1}
                              />
                            </div>
                            <div className="applyName">
                              <div title={item.ProcessName}>{item.ProcessName}</div>
                              <div>v{item.ProcessVersion}</div>
                            </div>
                          </div>
                        </div>
                      );
                    })}

                    {Array.from({ length: 9 }).map((item: any) => {
                      return (
                        <div className="cardItemContainer" key={item?.taskId || ''} >
                          <div className="test-applyItem" />
                        </div>
                      );
                    })}
                  </div>
                </div>
                {pageComponent}
              </>
            :
            !loading && <NoData />
        }
      </Spin>
    </div >
  );
});

export default ProcessApply;
